package kr.hkit.androidcomplete02.service;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;

public class MessengerServiceTest extends Activity implements View.OnClickListener {
	private Messenger mService;
	private boolean mBound;
	private Intent intent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.service_messengerservicetest);
		findViewById(R.id.msn_btn).setOnClickListener(this);
		findViewById(R.id.msn_btn2).setOnClickListener(this);
		intent = new Intent("kr.hkit.androidcomplete02.service.MESSENGER");
	}

	@Override
	protected void onStart() {
		super.onStart();
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		unbindService(mConnection);
		mBound = false;
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound = false;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = new Messenger(service);
			mBound = true;
		}
	};
	
	@Override
	public void onClick(View v) {
		if(!mBound) return;
		Message msg = null;
		switch(v.getId()){
		case R.id.msn_btn:
			msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
			break;
		case R.id.msn_btn2:
			msg = Message.obtain(null, MessengerService.MSG_SAY_HI, 0, 0);
			break;
		}
		try {
			mService.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
}
